package pl.edu.agh.pros.proxy.logic.dao.register;

import java.util.Collection;

import pl.edu.agh.pros.conf.RegistrationConstants;
import pl.edu.agh.pros.proxy.logic.dao.AppConfigurationDAO;
import pl.edu.agh.pros.proxy.logic.dao.common.AbstractDAO;
import pl.edu.agh.pros.proxy.model.AppConfiguration;
import pl.edu.agh.pros.proxy.model.RegisteredClient;

public class RegisteredClientDAO extends AbstractDAO<RegisteredClient> {

	private static final RegisteredClientDAO instance = new RegisteredClientDAO();

	private RegisteredClientDAO() {
		super(RegisteredClient.class);
	}

	public static RegisteredClientDAO getInstance() {
		return instance;
	}

	public Long registerClient(String appKey, String devId, String xmppAddress) {
		RegisteredClient registeredClient = this.getObject("appKey==param1 && devId==param2",
				"String param1, String param2", appKey, devId);
		if (registeredClient == null && appKey.equals(getProviderAppKey(appKey))) {
			registeredClient = this.getObject("appKey==param1", "String param1", appKey);
		}
		if (registeredClient == null) {
			registeredClient = new RegisteredClient();
			registeredClient.setAppKey(appKey);
			registeredClient.setDevId(devId);
		}
		registeredClient.setXmppAddress(xmppAddress);
		registeredClient.setRegistrationTime(System.currentTimeMillis());
		this.save(registeredClient);
		return RegistrationConstants.CLIENT_REGISTRATION_DURATION;
	}

	public String getClientXmppAddress(String appKey, String devId) {
		if (devId == null) {
			return getProviderXmppAddress(appKey);
		}
		RegisteredClient registeredClient = this.getObject("appKey==param1 && devId==param2",
				"String param1, String param2", appKey, devId);
		if (registeredClient == null) {
			return null;
		} else {
			return registeredClient.getXmppAddress();
		}
	}

	public String getProviderXmppAddress(String appKey) {
		RegisteredClient client = this.getObject("appKey==param1", "String param1", getProviderAppKey(appKey));
		if (client != null) {
			return client.getXmppAddress();
		}
		return null;
	}

	public void clearExpiredUsers() {
		Collection<RegisteredClient> expiredClients = this.getObjects("registrationTime < param1", "Long param1",
				System.currentTimeMillis() - RegistrationConstants.CLIENT_REGISTRATION_DURATION);
		this.deleteAll(expiredClients);
	}

	private String getProviderAppKey(String appKey) {
		AppConfiguration appCfg = AppConfigurationDAO.getInstance().getObject("clientAppKey==param1", "String param1",
				appKey);
		if (appCfg == null) {
			appCfg = AppConfigurationDAO.getInstance().getObject("providerAppKey==param1", "String param1", appKey);
			if (appCfg == null) {
				return null;
			}
		}
		return appCfg.getProviderAppKey();
	}
}